package io.github.javpower.gifweb.controller;


import io.github.javpower.gifweb.entity.Template;
import io.github.javpower.gifweb.service.TemplateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.List;
import java.util.UUID;

//管理平台页面
@RestController
@RequestMapping("/api/templates")
public class TemplateController {

    @Autowired
    private TemplateService templateService;
    @PostMapping("/add")
    public ResponseEntity<Template> createTemplate(@RequestParam("gifFile") MultipartFile gifFile, @RequestParam("templateFile") MultipartFile templateFile) {
        try {
            String gifBase64 = Base64.getEncoder().encodeToString(gifFile.getBytes());
            String templateParams = readTextFile(templateFile);
            Template template = new Template();
            template.setTemplateId(UUID.randomUUID().toString());
            template.setGifBase64(gifBase64);
            template.setTemplateParams(templateParams);
            return ResponseEntity.ok(templateService.saveTemplate(template));
        } catch (IOException e) {
            return ResponseEntity.badRequest().build();
        }
    }
    @PostMapping("/get/{templateId}")
    public ResponseEntity<Template> getTemplate(@PathVariable String templateId) {
        Template template = templateService.getTemplate(templateId);
        if (template == null) {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(template);
    }

    @PostMapping("/list")
    public ResponseEntity<List<Template>> getAllTemplates() {
        return ResponseEntity.ok(templateService.getAllTemplates());
    }

    @PostMapping("/del/{templateId}")
    public ResponseEntity<Void> deleteTemplate(@PathVariable String templateId) {
        templateService.deleteTemplate(templateId);
        return ResponseEntity.noContent().build();
    }

    public String readTextFile(MultipartFile file) throws IOException {
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(file.getInputStream(), StandardCharsets.UTF_8))) {
            StringBuilder content = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                content.append(line).append("\n");
            }
            return content.toString();
        }
    }
}